from flask import Blueprint, request, jsonify
from flask_cors import cross_origin
from app import db
from app.models import User
import base64
import os
from datetime import datetime

api_bp = Blueprint('api', __name__)

@api_bp.route('/health')
@cross_origin()
def health_check():
    """健康检查端点"""
    try:
        db.session.execute('SELECT 1')
        return jsonify({
            'status': 'healthy',
            'database': 'connected',
            'environment': os.environ.get('FLASK_ENV', 'development')
        }), 200
    except Exception as e:
        return jsonify({
            'status': 'unhealthy',
            'error': str(e)
        }), 503

@api_bp.route('/version')
@cross_origin()
def version():
    """版本信息端点"""
    return jsonify({
        'application': 'SingVote API',
        'version': '2.0.0',
        'environment': os.environ.get('FLASK_ENV', 'development')
    })

@api_bp.route('/user-status', methods=['POST'])
@cross_origin()
def user_status():
    """检查用户是否已签字"""
    data = request.get_json()
    device_uuid = data.get('uuid')
    device_fingerprint = data.get('fingerprint')
    
    if not device_uuid or not device_fingerprint:
        return jsonify({
            'error': '设备信息不完整'
        }), 400
    
    # 首先通过UUID查找用户
    user = User.query.filter_by(device_uuid=device_uuid).first()
    
    # 如果没有找到，尝试通过设备指纹查找
    if not user:
        user = User.query.filter_by(device_fingerprint=device_fingerprint).first()
    
    return jsonify({
        'hasSigned': user is not None,
        'signature': user.signature if user else None
    })

@api_bp.route('/sign', methods=['POST'])
@cross_origin()
def sign():
    """提交签字"""
    try:
        data = request.get_json()
        user_ip = request.remote_addr  # 保留IP作为备用信息
        signature_data = data.get('signature_data')
        signature_name = data.get('signature_name')
        room_number = data.get('room_number')
        device_uuid = data.get('device_uuid')
        device_fingerprint = data.get('device_fingerprint')
        signature_time = data.get('signature_time')
        
        if not signature_data or not signature_name:
            return jsonify({
                'error': '请完成签字并输入姓名'
            }), 400
        if not room_number:
            return jsonify({
                'error': '请填写门牌号'
            }), 400
        if not device_uuid or not device_fingerprint:
            return jsonify({
                'error': '设备信息不完整，请刷新页面重试'
            }), 400
        
        # 检查是否已签字（通过UUID或设备指纹）
        existing_user = User.query.filter(
            (User.device_uuid == device_uuid) | 
            (User.device_fingerprint == device_fingerprint)
        ).first()
        
        if existing_user:
            return jsonify({
                'error': '您已经签过字了'
            }), 400
        
        # 验证和处理签名数据格式
        base64_data = None
        if signature_data.startswith('data:image/'):
            try:
                base64_data = signature_data.split(',')[1] if ',' in signature_data else signature_data
            except IndexError:
                return jsonify({
                    'error': '签字数据格式错误，请重新签字'
                }), 400
        else:
            base64_data = signature_data
        
        # 验证 base64 数据是否有效
        try:
            decoded_data = base64.b64decode(base64_data)
        except Exception as e:
            return jsonify({
                'error': '签字数据格式错误，请重新签字'
            }), 400
        
        # 保存签字
        new_user = User(
            ip=user_ip,
            device_uuid=device_uuid,
            device_fingerprint=device_fingerprint,
            signature=signature_name.strip(),
            room_number=room_number.strip(),
            signature_image=base64_data,
            created_at=datetime.fromisoformat(signature_time) if signature_time else datetime.now()
        )
        db.session.add(new_user)
        db.session.commit()
        
        return jsonify({
            'message': '感谢您的签字！'
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'error': '签字保存失败，请重试'
        }), 500

@api_bp.route('/user-signature', methods=['POST'])
@cross_origin()
def get_user_signature():
    """获取当前用户的签字"""
    data = request.get_json()
    device_uuid = data.get('uuid')
    device_fingerprint = data.get('fingerprint')
    
    if not device_uuid or not device_fingerprint:
        return jsonify({'signature': None})
    
    # 首先通过UUID查找用户
    user = User.query.filter_by(device_uuid=device_uuid).first()
    
    # 如果没有找到，尝试通过设备指纹查找
    if not user:
        user = User.query.filter_by(device_fingerprint=device_fingerprint).first()
    
    if user:
        return jsonify({
            'signature': {
                'signature': user.signature,
                'signature_image': user.signature_image,
                'created_at': user.created_at,
                'room_number': user.room_number
            }
        })
    else:
        return jsonify({'signature': None})

@api_bp.route('/all-signatures')
@cross_origin()
def get_all_person_signatures():
    """获取所有人员的签字信息（不含敏感数据）"""
    all_users = User.query.order_by(User.created_at.desc()).all()
    signatures = []
    
    for user in all_users:
        signatures.append({
            'id': user.id,
            'signature': user.signature,
            'room_number': user.room_number,
            'created_at': user.created_at.isoformat() if user.created_at else None,
            'signature_image': user.signature_image  # 新增签名图片字段
        })
    
    return jsonify({
        'signatures': signatures,
        'total': len(signatures)
    })
    
@api_bp.route('/statistics')
@cross_origin()
def get_statistics():
    """获取签字统计"""
    total_signatures = User.query.count()
    target_signatures = 667  # 目标签字数
    progress = min(round((total_signatures / target_signatures) * 100, 1), 100)
    
    return jsonify({
        'total_signatures': total_signatures,
        'target_signatures': target_signatures,
        'progress': progress
    })

@api_bp.route('/admin/signatures')
@cross_origin()
def get_all_signatures():
    """管理员查看所有签字记录"""
    all_users = User.query.all()
    signatures = []
    
    for user in all_users:
        signatures.append({
            'id': user.id,
            'ip': user.ip,
            'device_uuid': user.device_uuid,
            'device_fingerprint': user.device_fingerprint,
            'signature': user.signature,
            'signature_image': user.signature_image
        })
    
    return jsonify({
        'signatures': signatures,
        'total': len(signatures)
    })

@api_bp.route('/signature/download/<int:user_id>')
@cross_origin()
def download_signature(user_id):
    """下载指定用户的签字图片"""
    user = User.query.get_or_404(user_id)
    
    if not user.signature_image:
        return jsonify({'message': '该用户没有签字图片'}), 404
    
    try:
        return jsonify({
            'user_id': user_id,
            'signature_name': user.signature,
            'signature_data': user.signature_image
        })
    except Exception as e:
        return jsonify({'message': '签字图片数据损坏'}), 500

@api_bp.route('/check-password', methods=['POST'])
@cross_origin()
def check_password():
    """检查密码端点"""
    data = request.get_json()
    password = data.get('password')
    if password == '123qwe':
        return jsonify({'success': True})
    else:
        return jsonify({'success': False}), 401
